package com.ryan.notify.ad;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;

import com.ryan.notify.ad.model.AdResult;

public abstract class AbstractAd implements IAd {

    @Override
    public AdResult check(Context ctx) {
        AdResult result = new AdResult(ctx.getPackageName());
        
        if(getActivitys()!=null){
            checkActivity(ctx,result);
        }
        
        if(result.isAd())
            return result;
        
        if(getMetaDatas()!=null){
            checkMetaData(ctx,result);
        }
        
        
        return result;
    }
    
    private void checkActivity(Context ctx,AdResult result){
        for (String activity : getActivitys()) {
            if(activity!=null){
                try {
                    ctx.getClassLoader().loadClass(activity);
                    setChecked(ctx,result,activity);
                    return ;
                } catch (ClassNotFoundException e) {
//                    LogUtil.e("E", "e",e);
                }    
            }
                    
        }
    }
    
    private void checkMetaData(Context ctx,AdResult result){
        for (String metaData : getMetaDatas()) {
            if(metaData!=null){
                try {
                    ApplicationInfo appInfo = ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(),PackageManager.GET_META_DATA);
                    Bundle bundle = appInfo.metaData;
                    if(bundle==null){
                        continue;
                    }
                    String value = bundle.getString(metaData);
                    if(value!=null){
                        setChecked(ctx,result,metaData);
                        return ;
                    }
                } catch (NameNotFoundException e) {
//                    LogUtil.e("E", "e",e);
                }    
            }
                    
        }
    }
    
    private void setChecked(Context ctx,AdResult result,String info){
        result.setAd(true);
        result.setAdName(getAdName());
        result.setExtraInfo(info);
    }
    
}
